package org.tzw.template.utils;

import android.content.Context;
import android.graphics.Bitmap;
import android.media.MediaScannerConnection;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;

import org.tzw.template.logger.LocalLogger;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;

import cn.hutool.core.util.StrUtil;

public class Utils {
    public static boolean isNetworkAvailable(Context mContext) {
        ConnectivityManager cm = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (cm != null) {
            // 如果仅仅是用来判断网络连接　　　　　　
            // 则可以使用 cm.getActiveNetworkInfo().isAvailable();
            NetworkInfo[] info = cm.getAllNetworkInfo();
            if (info != null) {
                for (int i = 0; i < info.length; i++) {
                    if (info[i].getState() == NetworkInfo.State.CONNECTED) {
                        return true;
                    }
                }
            }
        }
        return false;
    }

    public static <T> Class<T> getGenericClass(Class<?> clazz) {
        Type superclass = clazz.getGenericSuperclass();
        if (superclass == null) {
            return null;
        }
        if(superclass instanceof ParameterizedType){
            return (Class<T>) ((ParameterizedType) superclass).getActualTypeArguments()[0];
        }
        return getGenericClass(clazz.getSuperclass());
    }

    // 获取进程pid对应的进程名
    private static String getProcessName(int pid) {
        BufferedReader reader = null;
        String processName = "";
        try {
            reader = new BufferedReader(new FileReader("/proc/" + pid + "/cmdline"));
            processName = reader.readLine();
            if (!TextUtils.isEmpty(processName)) {
                processName = processName.trim();
            }
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        } finally {
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException exception) {
                exception.printStackTrace();
            }
        }
        return processName;
    }

    public void saveCurrentViewToGallery(Context mContext, View rootView) {
        // Step 1: 将当前视图转换为 Bitmap
        rootView.setDrawingCacheEnabled(true);
        rootView.buildDrawingCache();
        Bitmap bitmap = rootView.getDrawingCache();

        if (bitmap == null) {
            return; // 如果无法获取 Bitmap，则退出
        }

        // Step 2: 定义保存路径
        File picturesDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
        File imageFile = new File(picturesDir, "screenshot_ai_health_report_" + System.currentTimeMillis() + ".png");

        try {
            // Step 3: 将 Bitmap 写入文件
            FileOutputStream fos = new FileOutputStream(imageFile);
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
            fos.flush();
            fos.close();

            // Step 4: 通知系统刷新媒体库
            MediaScannerConnection.scanFile(
                    mContext,
                    new String[]{imageFile.getAbsolutePath()},
                    null,
                    (path, uri) -> {
                        // 图片已成功添加到相册
                    }
            );
        } catch (IOException e) {
            Log.e("Utils", StrUtil.format("当前报告保存失败：{}", e.getCause()));
        } finally {
            // 清除 Drawing Cache
            rootView.setDrawingCacheEnabled(false);
            rootView.destroyDrawingCache();
        }
    }
}
